package cn.net.sichen.taobao.interceptor;

import cn.net.sichen.taobao.utils.HttpUtil;
import cn.net.sichen.taobao.utils.SSOClientUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SsoClientInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        Boolean isLogin = (Boolean) request.getSession().getAttribute("isLogin");

        if (isLogin != null && isLogin) {
            // 已经登录，放行
            return true;
        }

        String token = request.getParameter("token");
        if (!StringUtils.isEmpty(token)) {
            // token不为null, 则去单点登录中心进行验证
            String httpUrl = SSOClientUtil.SERVER_URL_PREFIX + "/verify";
            Map<String, String> params = new HashMap<String, String>();
            params.put("token", token);
            params.put("clientUrl", SSOClientUtil.getClientLogOutUrl());
            params.put("jsessionId", request.getSession().getId());

            try {
                String isVerify = HttpUtil.sendHttpRequest(httpUrl, params);
                if ("true".equals(isVerify)) {
                    // 认证通过
                    request.getSession().setAttribute("isLogin", true);
                    return true;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        SSOClientUtil.redirectToSSOURL(request, response);
        return false;
    }
}
